package com.ptl.bp.config;

import lombok.extern.slf4j.Slf4j;
import org.springframework.http.converter.HttpMessageConversionException;
import org.springframework.validation.FieldError;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;

import java.util.HashMap;
import java.util.Map;

@Slf4j
@RestControllerAdvice
public class GlobalExceptionHandler {

    @ExceptionHandler(MethodArgumentNotValidException.class)
    public ApiResult<String> handleValidationExceptions(MethodArgumentNotValidException ex) {
        log.error("MethodArgumentNotValidException", ex);
        Map<String, String> errors = new HashMap<>();
        ex.getBindingResult().getAllErrors().forEach(error -> {
            String fieldName = ((FieldError) error).getField();
            String errorMessage = error.getDefaultMessage();
            errors.put(fieldName, errorMessage);
        });
        return ApiResult.fail(errors.toString());
    }

    @ExceptionHandler(HttpMessageConversionException.class)
    public ApiResult<String> handleHttpMessageConversionException(HttpMessageConversionException ex) {
        log.error("HttpMessageConversionException", ex);
        return ApiResult.fail("请求参数有问题, 请检查");
    }

    @ExceptionHandler(BizException.class)
    public ApiResult<String> handleBizException(BizException e) {
        log.error("业务异常", e);
        return ApiResult.response(e.getCode(), null, e.getMessage());
    }

    @ExceptionHandler(Exception.class)
    public ApiResult<String> handleException(Exception e) {
        log.error("系统未知异常", e);
        return ApiResult.exception("服务器发生异常, 请稍后重试");
    }
}